<template>
  <div class="org-manage-list">
    <a-form-model :model="orgForm" ref="orgForm" :rules="rules">
      <a-table
        ref="orgTable"
        style="width: 100%; margin-bottom: 30px"
        :scroll="{ x: 1000 }"
        :columns="orgColumns"
        :data-source="treeData"
        :loading="isLoading"
        :pagination="false"
        :rowKey="(record) => record.id"
      >
        <template slot="department" slot-scope="text, record">
          <a-tooltip placement="top">
            <template slot="title">
              <span>功能暂未开放，敬请期待！</span>
            </template>
          </a-tooltip>
          <!-- <a-button type="primary" class="mr10" ghost @click="handleBusinessFlow(record)">业务审批配置</a-button> -->
          <a-button type="primary" class="mr10" ghost @click="handlePersonnel(record)">组织人员</a-button>
          <a-button type="primary" class="mr10" ghost @click="handleRole(record)">组织身份</a-button>
          <a-button type="primary" class="mr10" ghost @click="handleConfig(record)">资源配置</a-button>
          <a-button type="primary" v-if="record.smallTenancyStatus === 1" ghost @click="handleLine(record)">分组配置</a-button>
        </template>
        <template slot="operations" slot-scope="text, record">
          <a-button type="primary" class="mr10" @click="handleAdd(record)">新增子部门</a-button>
          <a-button type="primary" @click="handleEdit(record)">编辑</a-button>
        </template>
        <template slot="advancedOperations" slot-scope="text, record">
          <a-button v-if="record.id !== organizationId" type="danger" @click="handleDelete(record)">移除</a-button>
        </template>
      </a-table>
      <div class="record cursor-pointer" @click="handleRecordList"><a-icon type="file-done" class="mr10" />移除记录</div>
    </a-form-model>
    <organization-form ref="organizationForm" @success="getDepartmentTree"></organization-form>
    <select-group
      v-if="showModal"
      :showModal="showModal"
      :groupList="groupList"
      :departmentId="departmentIdOfNow"
      @closeGroup="closeGroup"
      @success="getDepartmentTree"
    >
    </select-group>
  </div>
</template>

<script>
import { orgColumns, tabMap } from "../../data";
import { getDepartmentTree, deleteDepartment } from "@/services/userManage";
import { getGroupList } from "@/services/group";
import organizationForm from "./organizationForm.vue";
import selectGroup from "./selectGroup.vue";
export default {
  name: "OrgManageList",
  components: {
    organizationForm,
    selectGroup
  },
  data() {
    return {
      orgColumns,
      treeData: [],
      isLoading: false,
      orgForm: {},
      organizationId: "",
      groupList: [],
      showModal: false,
      selectResourceGroupCode: [],
      resourceId: '',
      departmentIdOfNow: '',
      visible: '',
      rules: {
        name: [{ required: true, message: "不能为空", trigger: "blur" }]
      },
      expandedRowKeys: []
    };
  },
  created() {
    this.getDepartmentTree();
  },
  methods: {
    // 组织树权限tree
    async getDepartmentTree(params) {
      let currentRecord = null
      if (params) {
        // 1. 基于参数确定是否需要调用接口, 在编辑时会传递noRefresh：true
        const { noRefresh, needPopGroupConfWindow } = params
        if (needPopGroupConfWindow && noRefresh) {
          // 2. 编辑时，递归遍历找到匹配的部门记录
          currentRecord = this.getDepartmentRecordFromTree(params.id);
          currentRecord && this.handleLine(currentRecord);
          return
        }
      }
      // 3. loading起并刷新tree接口
      this.isLoading = true;
      try {
        let { data: { data, code } } = await getDepartmentTree();
        if (code !== 200) {
          return
        }
        this.treeData = data.departmentList || [];
        this.organizationId = data.departmentList[0].id;
        // 是否需要弹窗 这里是新增时，基于新数据来查找
        if (params?.needPopGroupConfWindow) {
          currentRecord = this.getDepartmentRecordFromTree(params.id);
          currentRecord && this.handleLine(currentRecord);
        }
      } catch (error) {
        console.log(error)
      } finally {
        this.isLoading = false;
      }
    },
    // 基于id, 从树形结构中过滤出当前部门
    getDepartmentRecordFromTree(id) {
      const recursionFn = (list) => {
        for (let i = 0; i<list.length; i++) {
          const item = list[i];
          if (item.id === id) {
            return item;
          }
          if (item.children?.length) {
            const result = recursionFn(item.children);
            if (result) return result;
          }
        }
      }
      return recursionFn(this.treeData);
    },
    // 取消
    cancel() {
      // 清除数据并跳转
      this.clearOrgForm();
    },
    checkValid() {
      let bol = false;
      this.$refs.orgForm.validate((valid) => {
        bol = Boolean(valid);
      });
      return bol;
    },
    clearOrgForm() {
      this.$refs.orgForm.clearValidate();
    },
    handleBusinessFlow(row) {
      this.$router.push({
        query: {
          id: row.id,
          key: tabMap.businessConfig,
          name: encodeURIComponent(row.name)
        }
      });
    },
    handlePersonnel(row) {
      console.log(row)
      this.$router.push({
        path: '/car-team/system-qiankun/departmentManage-personnel-qiankun',
        query: {
          id: row.id,
          key: tabMap.personnelManage,
          name: encodeURIComponent(row.name)
        }
      });
    },
    handleRole(row) {
      this.$router.push({
        path: '/car-team/system-qiankun/departmentManage-role-qiankun',
        query: {
          id: row.id,
          key: tabMap.roleMange,
          name: encodeURIComponent(row.name)
        }
      });
    },
    // 资源配置
    handleConfig(row) {
      this.$router.push({
        path: '/car-team/system-qiankun/departmentManage-resourceConfig-qiankun',
        query: {
          id: row.id,
          key: tabMap.resourceManage,
          name: encodeURIComponent(row.name)
        }
      });
    },
    handleAdd(record) {
      let params = {
        id: record.id
      };
      this.$refs.organizationForm.show(params, "add");
    },
    handleEdit(row) {
      let params = row;
      delete params.children;
      params.organizationId = this.organizationId;
      this.$refs.organizationForm.show(params, "edit");
    },
    async handleDelete(record) {
      const that = this;
      this.$confirm({
        title: "移除操作",
        content: () => (
          <div>
            你确定移除该部门<span style="color:red;"> {record.name} </span>吗？
          </div>
        ),
        onOk() {
          deleteDepartment(record.id).then((res) => {
            const {
              data: { code, message }
            } = res;
            if (code === 200) {
              that.$message.success("删除成功");
              that.getDepartmentTree();
              that.visible = false;
            } else {
              that.$message.error(message);
            }
          });
        },
        onCancel() {
        }
      });
    },
    handleRecordList() {
      this.$router.push({
        path: `/car-team/system-qiankun/departmentManage-orgRemoveRecordList-qiankun`,
        query: {
          key: tabMap.orgRemoveRecordList
        }
      });
    },
    async handleLine(record) {
      this.departmentIdOfNow = record.id;
      this.showModal = true;
      const { data } = await getGroupList({
        departmentId: this.departmentIdOfNow
      });
      if (data.code === 200) {
        this.groupList = data.data
      }
    },
    closeGroup() {
      this.showModal = false;
    }
  }
};
</script>
<style lang="less" scoped>
.empty-type {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 15% 0;
}
.record{
  display: inline-block;
  padding: 0px 20px 20px;
  color: #3d6cf7;
}
</style>
